<template>
  <massif-layout left-width="256px">
    <template #left>
      <div class="massifIndex">
        <div class="searchBox">
          <div class="title">
            <bar-title title="长势记录" style="background: none;" :tips="`（${total}）`" />
          </div>
          <div class="scbtn">
            <hover-search ref="hvScRef" :showPop="showPop">
              <div class="tscBox">
                <div class="sfInputItem">
                  <div class="scName"><img src="/src/assets/jh.png" alt="">品种</div>
                  <div class="valbox">
                     <plant-header-select v-model="searchInfo.plantingPlanId" 
                        @focus="onFocus(false)" 
                        @change="getChangePlantList" 
                        @init="changePlantList"
                        :clearable="false"
                        placeholder="选择方案"
                        width="100%"
                        class-name="newSelectStyle" /> 
                  </div>
                </div>
                <div class="sfInputItem">
                  <div class="scName"><img src="/src/assets/rq.png" alt="">日期</div>
                  <div class="valbox">
                    <my-date-picker v-model="time" style="width:260px;" 
                    @focus="onFocus(false)" 
                    @change="onFocus(true)" />
                  </div>
                </div>
                <div class="sfInputItem">
                  <div class="scName"><img src="/src/assets/zsqk.png" alt="">生育时期</div>
                  <div class="valbox">
                    <xuntian-select v-model="searchInfo.shengyuqiId"  
                    v-if="searchInfo.cropId"
                    @focus="onFocus(false)" 
                    @change="onFocus(true);"
                      :params="{ 
                        farmId: userStore.userInfo.farmId,
                        param1:searchInfo.cropId,
                        lovCode:'TANC_CROP_SHENGYUQI'
                      }"  
                      width="100%" class="newSelectStyle" />
                  </div>
                </div>
                <div class="sfInputItem">
                  <div class="scName"><img src="/src/assets/zsqk.png" alt="">长势情况</div>
                  <div class="valbox">
                    <xuntian-select v-model="searchInfo.growthId"  
                    v-if="searchInfo.cropId"
                      @focus="onFocus(false)" 
                       @change="onFocus(true);"
                      :params="{
                        farmId: userStore.userInfo.farmId,
                        param1:searchInfo.cropId,
                        lovCode:'TANC_GROWTH'
                        }" 
                        width="100%" class="newSelectStyle" />
                  </div>
                </div>
                <div class="sfInputItem">
                  <div class="scName"><img src="/src/assets/fzr.png" alt="">记录人</div>
                  <div class="valbox">
                    <user-select v-model="searchInfo.createId" 
                      @focus="onFocus(false)"
                      @change="onFocus(true);"
                      placeholder="选择记录人"
                      class="newSelectStyle" />
                  </div>
                </div>
                <div style="display: flex;justify-content: end;padding:20px 0 0 0;">
                  <el-button class="newBtnStyle" icon="circleClose" @click="closeSearchPop">取消</el-button>
                  <el-button class="newBtnStyle" type="primary" icon="search" @click="search">查询</el-button>
                </div>
              </div>
            </hover-search> 
          </div>
        </div>

        <div class="listBox">
          <task-min-list :list="records || {}" :type="2" @itemClick="lookDetail" />
          <div v-if="records && records.length == 0" style="text-align: center;padding: 20px 0;color: #999;">暂无数据
          </div>
        </div>
        <div class="bottom-page">
          <my-pagination :total="total" :page="page" :finish="(page * limit) >= total" :limit="limit" @goPage="toPage" />
        </div>
      </div>
    </template>
    <div style="width: 100%; height: 100%;position: relative;">
      <div class="bottom-view">
         <div>长势状况图例</div>
         <div class="item" v-for="item in bottomList">
            <i :style="{'backgroundColor':item.color}"></i>
            <span>{{item.text}}</span>
         </div>
      </div>    
      <landMap ref="refLandMap" 
        :plantingPlanId="searchInfo.plantingPlanId"  
        :selectLandList="selectLandList"
        @onOpen="getLandInfoList"
      />
    </div>
     <!--长势地块定位-->
     <detail v-if="rightBlockFlag" :details="details" @close="rightBlockFlag = false"  />
     <detailList v-if="rightListBlockFlag" :list="landInfoList" @close="rightListBlockFlag = false" />
     
  </massif-layout>
</template>

<script setup>
// 这里的name是为了做页面缓存，其值要跟路由里面的name值一样

import { nextTick, ref, reactive, onMounted } from 'vue'
import massifLayout from '../components/layout.vue'
import myPagination from '@/components/custom/myPagination.vue'
import detail from './components/detail.vue'
import detailList from './components/detailList.vue'
import barTitle from '../task/components/barTitle.vue'
import taskMinList from '../components/taskMinList.vue'
import hoverSearch from '../components/hoverSearch.vue'
import plantHeaderSelect from '@/components/custom/plantHeaderSelect.vue'
import userSelect from '@/components/custom/userSelect.vue'
import xuntianSelect from '@/components/custom/xuntianSelect.vue'
import myDatePicker from '@/components/custom/myDatePicker.vue'
import {getFarmGrowthList, getRecordDetail,getLandGrowthCount} from '@/api/plant'
import { useUserStore } from '@/pinia/modules/user'
import landMap from "./components/landMap.vue";
import {VXETable} from 'vxe-table'
import { useRouter } from 'vue-router'
const router = useRouter()

const userStore = useUserStore()
const rightBlockFlag = ref(false)
const rightListBlockFlag = ref(false)
const searchInfo = ref({})
const page = ref(1)
const limit = ref(10)
const total = ref(0)
const records = ref('')
const time = ref('')
const details = ref({})
const hvScRef = ref(null)
const showPop = ref(true)
const selectLandList = ref([])
const landInfoList = ref([])

const bottomList = reactive([
  {color:'rgb(232, 164, 17)',text:'过旺',count:1},
  {color:'rgb(56, 162, 138)',text:'壮',count:2},
  {color:'rgb(122, 194, 156)',text:'中',count:3},
  {color:'rgb(234, 76, 76)',text:'差',count:4}
])

onMounted(async () => {
  searchInfo.value.farmId = userStore.userInfo.farmId
  searchInfo.value.companyId = userStore.userInfo.companyId
  const { currentRoute } = router


  if(currentRoute.value?.query?.plantingPlanTaskRecordId){
    let params ={
      plantingPlanTaskRecordId:currentRoute.value?.query?.plantingPlanTaskRecordId,
      companyId:currentRoute.value?.query?.companyId,
      farmId:currentRoute.value?.query?.farmId,
      plantingPlanId:currentRoute.value?.query?.plantingPlanId
    }
   window.setTimeout(() => {
      lookDetail(params)
      changePlantList({value:currentRoute.value?.query?.plantingPlanId,cropId:''})
    }, 1000);
  }

})

const getLandHandCountList = async ()=>{
  if(!searchInfo.value.plantingPlanId){return false}
  VXETable.modal.message({
            content: '正在加载长势记录',
            mask:true,
            top:500,
            duration:-1, 
            id:'loading-growth',
            status: 'loading'
    })
   let res = await  getLandGrowthCount({plantingPlanId:searchInfo.value.plantingPlanId,taskRecordType:2})
    if(res.success){
          let list = res.data ||{}
          let landIds =[]
          Object.keys(list).forEach((key)=> { landIds.push({farmLandId:Number(key),growthColor:list[key]})})
          selectLandList.value = landIds
          VXETable.modal.close('loading-growth')
      }
}

const changePlantList =async (item)=>{
  searchInfo.value.plantingPlanId=item.value
  searchInfo.value.cropId=item.cropId
  page.value = 1
  total.value=0
  onFocus(false)
  get_farm_record_list()
  window.setTimeout(() => {
     getLandHandCountList()
  }, 3000);
}
const getChangePlantList =async (item)=>{
  searchInfo.value.plantingPlanId=item.value
  searchInfo.value.cropId=item.cropId
  page.value = 1
  total.value=0
  onFocus(false)
  // get_farm_record_list()
  // getLandHandCountList()
}

// 农事记录列表
const get_farm_record_list = async () => {
  if (time.value) {
    searchInfo.value.createTimeStart = time.value[0] + ' 00:00:00'
    searchInfo.value.createTimeEnd = time.value[1] + ' 00:00:00'
  } else {
    delete searchInfo.value.createTimeStart
    delete searchInfo.value.createTimeEnd
  }
  const res = await getFarmGrowthList({
    page: page.value,
    limit: limit.value,
    // farmId:farmId.value || null,
    farmingType: 2,
    queryEntry: 1, // 种植系统固定为1
    ...searchInfo.value,

  })
  records.value = res.data
  total.value = res.total
  rightBlockFlag.value = false
}

const search = () => {
  page.value = 1
  total.value=0
  closeSearchPop()
  get_farm_record_list()
  getLandHandCountList()
}

const toPage = (pageNum) => {
  page.value = pageNum
  get_farm_record_list()
}

const onFocus =(type)=>{
  showPop.value = type
}

//获取当前地块的所有操作记录信息
const getLandInfoList =async(item)=>{
  let res =await getFarmGrowthList({
    page:1,
    limit:100,
    farmLandId:item.farmLandId,
    plantingPlanId:searchInfo.value.plantingPlanId,
    farmId:userStore.userInfo.farmId
  })
  if(res.success){
    rightListBlockFlag.value = true
    rightBlockFlag.value = false
    landInfoList.value = res.data ||[]
  }
}

const lookDetail = async (item) => {
  VXETable.modal.message({
            content: '正在加载长势记录',
            mask:true,
            top:500,
            duration:-1, 
            id:'loading-growth',
            status: 'loading'
    })
  searchInfo.value.farmId = item.farmId
  const res = await getRecordDetail(item.plantingPlanTaskRecordId)
  if (res.success) {
      rightBlockFlag.value = true
      rightListBlockFlag.value = false
      details.value = res.data
      let list = res.data?.landGrowthMap ||{}
      let landIds =[]
      Object.keys(list).forEach((key)=> { landIds.push({farmLandId:Number(key),growthColor:list[key]})})
      selectLandList.value = landIds
      VXETable.modal.close('loading-growth')
  }
}


const closeSearchPop = () => {
  hvScRef.value.close()
}


</script>

<style lang="scss" scoped>
.massifIndex {
  box-sizing: border-box;
  display: flex;
  flex-flow: column;
  height: 100%;
  padding: 0;

  //overflow: hidden;
  .searchBox {
    display: flex;
    padding: 0 0 0 10px;
    border-bottom: 1px solid #F4F4F4;

    .title {
      flex: 1;
    }

    .scbtn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 50px;
      height: 100%;
    }
  }

  .listBox {
    box-sizing: border-box;
    //flex: 1;
    height: calc(100vh - 158px);
    flex-shrink: 0;
    width: 100%;
    padding: 0;
    overflow: hidden;
    overflow-y: auto;
  }

  .bottom-page {
    box-sizing: border-box;
    flex-shrink: 0;
    height: 30px;
    padding: 0;
  }
}

.rdList {
  list-style: none;
  padding: 0;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;

  li {
    display: flex;
    box-sizing: border-box;
    min-height: 80px;
    line-height: 20px;
    padding: 8px;
    background-color: #f8f7f7;
    cursor: pointer;

    &.selected {
      background-color: rgb(72, 178, 122, 0.2);
    }

    &+li {
      margin-top: 10px;
    }

    .tBox {
      flex: 1;

      p {
        font-size: 12px;
      }
    }
  }
}

.tscBox {
  width: 390px;
  padding: 20px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  position: relative;
  .sfInputItem {
    display: flex;
    height: 38px;
    align-items: center;

    &+.sfInputItem {
      margin-top: 10px;
    }

    .valbox {
      flex: 1;
    }

    .scName {
      display: flex;
      align-items: center;
      width: 110px;
      font-size: 16px;
      color: #333333;

      img {
        display: block;
        width: 20px;
        margin: 0 6px 0 0;
      }
    }
  }
}
</style>

<style lang="scss">
.datebox {
  .el-date-editor {
    width: 100%;
  }
}

.el-select {
  &.newSelectStyle {
    .el-input__inner {
      height: 38px !important;
      line-height: 38;
      padding-right: 0;
      overflow: hidden;
      font-size: 14px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
    }

    .el-input__suffix {
      padding: 0 8px;
      background: #F9F9F9;
      height: 36px;
      top: 1px;
      right: 1px;

      .el-icon {
        color: #04AE70;
        font-weight: bold;
      }
    }

    .el-input__icon {
      line-height: 38;
      height: 36px !important;
    }

    .el-input.is-focus .el-input__inner,
    .el-input__inner:focus {
      border-color: rgba(0, 0, 0, 0.15) !important;
    }
  }
}

.el-button {
  &.newBtnStyle {
    height: 38px;
  }
}
.bottom-view{
  position: absolute;
  bottom:10px;
  left:10px;
  background-color: #00000080;
  z-index:999;
  color: #fff;
  font-size:10px;
  padding:8px;
  border:1px solid #bfbfbf;
  .item{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top:5px;
    i{
      height:15px;
      width:30px;
      background-color: red;
    }
    span{
      padding-left:2px;
      font-size:12px;
    }
  }
}
</style>
